package com.dxl.lanju.dao;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;

import com.dxl.common.model.Page;
import com.dxl.common.utils.SqlBuilder;
import com.dxl.common.utils.Utils;
import com.dxl.dao.common.BaseDao;
import com.lanju.bean.ProductSkuBean;
import com.lanju.entity.Product;
import com.lanju.entity.ProductSku;

/**
 * 产品管理DAO
 * @author 邓小林
 */
@Repository
public class ProductDao extends BaseDao {
	private static final Logger LOG = Logger.getLogger(ProductDao.class);
	
	public Page<Product> list(String cateId, String keyword, Integer state, Integer pageNo, Integer pageSize) {
		SqlBuilder sb = new SqlBuilder("select a.* from product a, product_cate b where a.cate_id = b.id");
		if (Utils.isNotBlank(cateId)) {
			sb.appendStatement(" and b.id = ").appendParamValue(cateId);
		}
		if (Utils.isNotBlank(keyword)) {
			keyword = keyword.trim();
			sb.appendStatement(" and a.name like ").appendParamValue("%" + keyword + "%");
		}
		if (Utils.isNotNull(state)) {
			sb.appendStatement(" and a.state = ").appendParamValue(state);
			sb.appendStatement(" and b.state = ").appendParamValue(state);
		}
		sb.appendStatement(" order by a.created_time desc");
		return this.list(Product.class, sb.toStatement(), sb.toParams(), pageNo, pageSize);
	}
	
	public Page<ProductSkuBean> listProductSku(String cateId, String keyword, Integer state, Integer pageNo, Integer pageSize) {
		SqlBuilder sb = new SqlBuilder("select a.*, b.name, b.path_sl, b.description from product_sku a, product b, product_cate c where a.prod_id = b.id and b.cate_id = c.id");
		if (Utils.isNotBlank(cateId)) {
			sb.appendStatement(" and c.id = ").appendParamValue(cateId);
		}
		if (Utils.isNotBlank(keyword)) {
			keyword = keyword.trim();
			sb.appendStatement(" and b.name like ").appendParamValue("%" + keyword + "%");
		}
		if (Utils.isNotNull(state)) {
			sb.appendStatement(" and a.state = ").appendParamValue(state);
			sb.appendStatement(" and b.state = ").appendParamValue(state);
			sb.appendStatement(" and c.state = ").appendParamValue(state);
		}
		sb.appendStatement(" order by a.created_time desc");
		return this.list(ProductSkuBean.class, sb.toStatement(), sb.toParams(), pageNo, pageSize);
	}
	
	public List<ProductSku> listSku(String prodId) {
		SqlBuilder sb = new SqlBuilder("select * from product_sku where prod_id = ").appendParamValue(prodId).appendStatement(" order by created_time desc");
		return this.list(ProductSku.class, sb.toStatement(), sb.toParams());
	}
	
	public boolean exist(String name) {
		SqlBuilder sb = new SqlBuilder("select * from product where name = ").appendParamValue(name);
		return this.count(sb.toStatement(), sb.toParams()) > 0;
	}
}
